using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Windows;
using System.Windows.Controls;

namespace Controls
{
    public class TabControlEx : TabControl
    {
        public static readonly DependencyProperty DefaultStyleProperty = DependencyProperty.Register("DefaultStyle", typeof(bool), typeof(TabControlEx), new UIPropertyMetadata(true));

        public bool DefaultStyle
        {
            get
            {
                return (bool)GetValue(DefaultStyleProperty);
            }
            set
            {
                SetValue(DefaultStyleProperty, value);
            }
        }

        protected override void OnItemsChanged(NotifyCollectionChangedEventArgs e)
        {
            base.OnItemsChanged(e);
            RefreshTabItemStyle();
        }

        public void RefreshTabItemStyle()
        {
            List<TabItem> list = (from TabItem s in base.Items
                                  where s.Visibility == Visibility.Visible
                                  select s).ToList();
            for (int i = 0; i < list.Count; i++)
            {
                list[i].Margin = new Thickness(i * -10, -2.0, i * 10, 0.0);
                if (DefaultStyle)
                {
                    list[i].SetResourceReference(FrameworkElement.StyleProperty, (i == 0) ? "TabItemStylesmall" : "TabItemStyleSelectFalse");
                }
            }
            if (list.Count == 0)
            {
                base.SelectedIndex = -1;
            }
            else if (!list.Contains(base.SelectedItem))
            {
                list[0].IsSelected = true;
            }
        }
    }
}
